#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <errno.h>

static int sockfd;  /* socket file descriptor for the IP connection */

int client_connect(char *host_or_ipaddr, unsigned short port)
{
   socklen_t remote_len;
   struct sockaddr_in remote;
   struct hostent *he;
   int status;

   he=gethostbyname2(host_or_ipaddr,AF_INET);
   if (he==NULL)
   {
      printf("Host nicht gefunden: %s\n",host_or_ipaddr);
      return 1;
   }
   // Create socket file descriptor
   sockfd=socket(AF_INET,SOCK_STREAM,0);
   if (sockfd==-1)
   {
      perror("socket");
      return 2;
   }

   remote.sin_family=AF_INET;
   //inet_aton(he->h_addr,&remote.sin_addr);
   remote.sin_addr=*((struct in_addr*) he->h_addr);
   remote.sin_port=htons(port);
   remote_len=sizeof(struct sockaddr_in);

   // Create connection to remote host
   status=connect(sockfd, (const struct sockaddr*)&remote, remote_len);
   if (status==-1)
   {
      perror("connect");
      return 2;
   }
   return 0;
}

int get_sockfd(void)
{
   return sockfd;
}
